/*
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-06-25 18:28:54
 * @LastEditTime: 2024-06-26 11:17:19
 * @FilePath: \project\src\permisstion.ts
 */
import router from '@/router'
import setting from './setting'
// 进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({showSpinner: false})
import useUserStore from './store/modules/user'
import pinia from './store'
let userStore = useUserStore(pinia)

//前置守卫
router.beforeEach(async (to:any, from:any ,next:any) =>{
  document.title = setting.title+'-'+to.meta.title
  nprogress.start()
  let token = userStore.token
  let username = userStore.username
  if(token) {
    if(to.path == '/login') {
      next('/')
    } else {
      if(username) {
        next()
      } else {
        try{
          await userStore.getUserInfo()
          next()
        } catch(err) {
          await userStore.userLogout()
          next({path:'/login', query:{redirect:to.path}})
        }
      }
    }
  } else {
    if(to.path == '/login'){
      next()
    } else {
      next({path:'/login', query:{redirect:to.path}})
    }
  }
})

// 后置守卫
router.afterEach((to:any, from:any)=>{
  nprogress.done()
})